import {Component, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {PlanService} from "@train/plan/plan.service";
import {ActivatedRoute, NavigationExtras, Params, Router} from "@angular/router";

import {ToolsService} from "@shared/service/tools/tools.service";
import {ImageServeService} from "@shared/service/image/image-serve.service";
import {AuthService} from "@shared/service/auth/auth.service";
import {TrainClassScheduleVO, TrainTeachProcess} from "@interface/index";


@Component({
  selector: 'seed-edit-teaching-process',
  templateUrl: './edit-teaching-process.component.html',
  styleUrls: ['./edit-teaching-process.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class EditTeachingProcessComponent implements OnInit {
  public classSchedule: TrainClassScheduleVO;
  // private _classScheduleId: number;
  private _trainTeachProcess: TrainTeachProcess;
  public organizingFormsImg: Array<any>;
  public teachProcessDefault: TrainTeachProcess = new TrainTeachProcess();
  @ViewChild('duration') duration;
  @ViewChild('organizingForms') organizingForms;
  @ViewChild('trainingTimes') trainingTimes;
  constructor(
    private _planService: PlanService,
    private _route: ActivatedRoute,
    private _router: Router,
    private _toolService: ToolsService,
    private _imgService: ImageServeService,
    private _authService: AuthService
  ) {
    this._trainTeachProcess = new TrainTeachProcess();
    this.organizingFormsImg = [
      {
        active: this.getImage('train/teach_type_1.png'),
        inactive: this.getImage('train/teach_type_1_n.png'),
        vaule: '1',
        isChecked: false
      },
      {
        active: this.getImage('train/teach_type_2.png'),
        inactive: this.getImage('train/teach_type_2_n.png'),
        vaule: '2',
        isChecked: false
      },
      {
        active: this.getImage('train/teach_type_3.png'),
        inactive: this.getImage('train/teach_type_3_n.png'),
        vaule: '3',
        isChecked: false
      },
      {
        active: this.getImage('train/teach_type_4.png'),
        inactive: this.getImage('train/teach_type_4_n.png'),
        vaule: '4',
        isChecked: false
      }
    ];
    this._route.params
      .switchMap((params: Params) => {
        if (!params['classScheduleId']) {
          return;
        }
        this._trainTeachProcess.classScheduleId = params['classScheduleId'];
        this.fetchTeachProcessByClassscheduleId(params['classScheduleId']);
        return this._route.queryParams;
      }).subscribe((params: TrainClassScheduleVO) => {
      this.classSchedule = params;
      this._trainTeachProcess['authOrgId'] = this._authService.getAuthOrgId();
      if (params['type'] === 'save') {
        this._trainTeachProcess['id'] = parseInt(params['id'].toString(), 10);
      }
    });
  }

  getImage(src: string) {
    return this._imgService.getImage(src);
  }

  /**
   * @description 获取选中图片的value赋值organizingForms上
   * @author @chenwh576
   * @date 2018/1/4 下午7:19
   */
  getCurrentImgSrc(query): string {
    if (query.isChecked) {
      return query.active;
    } else {
      return query.inactive;
    }
  }

  handleOrganizingFormsIsChecked(query) {
    const isChecked = query.isChecked;
    this.organizingFormsImg.forEach((item, index) => {
      item.isChecked = false;
    });
    query.isChecked = !isChecked;
    if (query.isChecked === true) {
      this._trainTeachProcess.organizingForms = query.vaule;
    } else {
      this._trainTeachProcess.organizingForms = 0;
    }

  }

  /**
   * @description 保存TeachProcess选中的value
   * @author @chenwh576
   * @date 2018/1/6 下午4:26
   */
  saveTeachProcessValue(query, key: string) {
    const _trainTeachProcess = this._trainTeachProcess;
    switch (key) {
      case 'duration': {
        _trainTeachProcess.duration = query;
        break;
      }
      case 'trainingTimes': {
        _trainTeachProcess.trainingTimes = query;
        break;
      }
      case 'measureWay': {
        _trainTeachProcess.measureWay = query;
        break;
      }
      case 'questionWay': {
        _trainTeachProcess.questionWay = query;
        break;
      }
      case 'organizingForms': {
        _trainTeachProcess.organizingForms = query;
        break;
      }
    }
  }

  /**
   * @description 保存/修改教学过程信息
   * @author @chenwh576
   * @date 2018/1/3 下午4:40
   * @param {number} classScheduleId
   * @return {Observable<SNSResult<number>>}
   */
  saveTeachProcess() {
    const data = this._trainTeachProcess;
    const duration = +data.duration;
    const trainingTimes = +data.trainingTimes;
    if (data.duration && (!Number.isInteger(duration) || duration > 200 || duration < 0)) {
      this._toolService.showToast('预计时长 请填写 0 - 200 之间的数字');
      return;
    }
    if (data.trainingTimes && (!Number.isInteger(trainingTimes) || trainingTimes > 500 || trainingTimes < 0)) {
      this._toolService.showToast('训练次数 请填写 0 - 500 之间的数字');
      return;
    }
    this._planService.saveTeachProcess(data)
      .subscribe(res => {
        if (res.result === '0') {
          this._toolService.showToast('添加成功');
          setTimeout(() => this.goToTrainDetailPage(), 1000);
        } else {
          this._toolService.showToast(res.msg);
        }
      });
  }

  goToTrainDetailPage() {
    const NavigationExtras: NavigationExtras = {
      queryParams: {
        subjectName: this.classSchedule.subjectName,
        teacherName: this.classSchedule.teacherName
      }
    };
    // this._router.navigate(['/train/plan/detail/', this._trainTeachProcess.classScheduleId], NavigationExtras);
    history.back();
  }

  get isDisabled(): boolean {
    const _trainTeachProcess = this._trainTeachProcess;
    if (!!_trainTeachProcess.duration
      || !!_trainTeachProcess.trainingTimes
      || !!_trainTeachProcess.measureWay
      || !!_trainTeachProcess.questionWay
      || !!_trainTeachProcess.organizingForms
    ) {
      return false;
    } else {
      return true;
    }
  }

  /**
   * @description 通过班级课时Id，查询教学过程信息
   * @author @chenwh576
   * @date 2018/1/3 下午4:40
   * @param {number} classScheduleId
   */
  fetchTeachProcessByClassscheduleId(classScheduleId: number) {
    this._planService.fetchTeachProcessByClassscheduleId(classScheduleId)
      .filter(res => res.result === '0')
      .subscribe(res => {
        res.data.forEach(each => {
          if (each.id === this._trainTeachProcess['id']) {
            this.teachProcessDefault = each;
          }
        });
        const processefault = this.teachProcessDefault;
        if (processefault.duration) {
          this._trainTeachProcess.duration =  processefault.duration;
          this.duration.nativeElement.value = processefault.duration;
        }
        if (processefault.trainingTimes) {
          this._trainTeachProcess.trainingTimes =  processefault.trainingTimes;
          this.trainingTimes.nativeElement.value = processefault.trainingTimes;
        }
        if (processefault.organizingForms > 0 ) {
          this._trainTeachProcess.organizingForms =  processefault.organizingForms;
          // console.log(this.organizingForms.nativeElement.children[Processefault.organizingForms]);
          this.organizingForms.nativeElement.children[processefault.organizingForms - 1].children[0].click();
        }
      });
  }
  ngOnInit() {
  }

}
